package com.example.androidproject.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.example.androidproject.widget.interfaces.OnPressCallback;

/**
 * FileName: LongPressTextView
 * Author: huangyuguang
 * Date: 2022/6/30
 * Description: 长按事件处理
 */
public class LongPressTextView extends AppCompatTextView {

    private long minLongClickTime = 500L;
    private boolean isLongClicked = false;
    private volatile boolean isPressDown = false;
    private boolean isRunnableFinish = true;
    private OnPressCallback onPressCallback;

    public LongPressTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setClickable(true);
    }

    public void setOnPressCallback(OnPressCallback onPressCallback) {
        this.onPressCallback = onPressCallback;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                isPressDown = true;
                isLongClicked = false;
                if(isRunnableFinish){ //定时执行完成了
                    handler.postDelayed(runnable, minLongClickTime);
                    isRunnableFinish = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                handler.removeCallbacks(runnable);
                isPressDown = false;
                isRunnableFinish = true;
                onCallback(true);
                break;
        }
        return super.onTouchEvent(event);
    }

    private void onCallback(boolean isStop){
        if(onPressCallback != null){
            onPressCallback.pressCallback(this,isStop);
        }
    }

    Handler handler = new Handler(Looper.getMainLooper());
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(isPressDown){
                if (isLongClicked){
                    onCallback(false);
                }else{
                    isLongClicked = true;
                }
                handler.postDelayed(this, 100);
            }else{
                isRunnableFinish = true;
            }
        }
    };

}
